package com.jy.modules.cims.buyback.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;

/**
 * 贷款回购导入
 */
@Service("com.jy.modules.cims.buyback.service.BuyBackImpService")
public class BuyBackImpService extends BuyBackCommonService {

	private static final Logger logger = LoggerFactory.getLogger(BuyBackImpService.class);
	/**
	 * 导入贷款回购excel
	 * @param creditDealList
	 * @param batchId
	 * @param redeemDate
	 * @throws Exception 
	 */
	public void doImportBuyBackExcel(List<CreditDetailDto> creditList, String batchId, String redeemDate, String contractCode) throws Exception {
		List<CreditDetailDto> validateList = new ArrayList<CreditDetailDto>();
		//校验excel
		checkBuyBackExcel(creditList, validateList);
		//按validateList、修改关系表（回购价格、本息和、匹债权金额、结算标识、保证金、服务费）
		updateRefBuyBack(validateList, batchId, contractCode);
		//更新批次表的回购价格总和
		buyBackDao.updateBatchBuyBack(batchId);
	}
	
	/**
	 * 修改关系表（回购价格、本息和、匹债权金额、结算标识、保证金、服务费）
	 * @param validateList
	 */
	private void updateRefBuyBack(List<CreditDetailDto> validateList, String batchId, String contractCode) {
		if (CollectionUtils.isNotEmpty(validateList)) {
			//更新债权明细表
			for (CreditDetailDto credit : validateList) {
				String transferId = credit.getTransferId();
				//匹债权金额
				BigDecimal matchAmt = null;
				if (credit.getBackMatchValue() != null) {
					matchAmt = credit.getBackMatchValue();
				} else {
					String repayType = getRepayType(contractCode);
					matchAmt = getMatchAmt(credit, contractCode, repayType);
				} 
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("transferId", transferId);
				map.put("backContractValue", credit.getDealMakeCreditorValue());//回购价格
				map.put("backTotalValue", credit.getBackTotalValue());//本息和
				map.put("backMatchValue", matchAmt);//匹债权金额
				map.put("settleFlg", CimsConstant.COST_STATUS_DJ);//结算状态
				map.put("serviceCharge", credit.getServiceCharge());//服务费
				map.put("guaranteeFee", credit.getGuaranteeFee());//担保费
				map.put("cautionMoney", credit.getCautionMoney());//保证金
				map.put("redeemDate", credit.getRedeemDate());//回购日期
				buyBackDao.updateRefBuyBack(map);
			}
		}
	}
	
	/**
	 * 校验excel
	 * @param creditList
	 * @param validateList
	 * @throws Exception
	 */
	private void checkBuyBackExcel(List<CreditDetailDto> creditList, List<CreditDetailDto> validateList) throws Exception {
		if (CollectionUtils.isEmpty(creditList)) {
			throw new RuntimeException("导入的excel中没有数据");
		}
		for (CreditDetailDto credit : creditList) {
			//转让编号 
			String transferId = credit.getTransferId();
			//回购价格不能为空
			BigDecimal buyBackAmt = credit.getDealMakeCreditorValue();
			//本息和不能为空
			BigDecimal totalAmt = credit.getBackTotalValue();
			if (buyBackAmt == null) {
				throw new RuntimeException("回购价格不能为空,转让编号="+transferId);
			}
			if (totalAmt == null) {
				throw new RuntimeException("本息和不能为空,转让编号="+transferId);
			}
			if (totalAmt.compareTo(buyBackAmt) < 0) {
				throw new RuntimeException("本息和必须大于等于回购价格,转让编号="+transferId);
			}
			
			//查询债权状态02已确认04泯灭
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
			dto.setTransferId(transferId);
			dto.setValidateState("1");
			searchParams.put("dto", dto);
			List<TCMmCreditDetailDTO> detailList = creditDetailService.searchTCMmCreditDetail(searchParams);
			if (CollectionUtils.isEmpty(detailList)) {
				throw new RuntimeException("债权表中查不到该债权,转让编号="+transferId);
			}
			dto = detailList.get(0);
			String creditStatus = dto.getCreditorStatus();
			if (!CimsConstant.CREDIT_STATUS_WIN.equals(creditStatus) 
					&& !CimsConstant.CREDIT_STATUS_END.equals(creditStatus) ) {
				logger.warn("债权状态=" + creditStatus + ",不是02已确认04泯灭,转让编号=" + transferId);
				continue;
			}
			
			//添加到有效list
			validateList.add(credit);
		}
	}
	
}
